﻿using System.Runtime.InteropServices;

namespace System.Security
{
    internal static class SecureStringExtensions
    {
        public static SecureString ConvertToSecureString(this string data)
        {
            SecureString result = new SecureString();
            foreach (char c in data) result.AppendChar(c);
            return result;
        }

        public static string ConvertToUnsecureString(this SecureString data)
        {
            IntPtr unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(data);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }
    }
}
